﻿using MebAppMarketplace.Biz;
using MebAppMarketplace.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MebAppMarketplace.Controllers
{
    /// <summary>
    /// 用户功能，包括登录和设置自己的密码
    /// </summary>
    [Authorize(Roles = "User")]
    public class UserController : Controller
    {
        public UserService userService { get; set; }
        [AllowAnonymous]
        public IActionResult Login()
        {
            return View();
        }
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login(string username, string password)
        {
            var result = await userService.LoginUser(username, password);
            if (result == Model.LoginResult.登录成功)
            {
                return Redirect("/");
            }
            ModelState.AddModelError("", result.ToString());
            return this.ViewError();
        }

        /// <summary>
        /// 用户首页，显示用户已购买App列表，app使用情况
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public IActionResult Index(int page)
        {
            var list = userService.GetUserList(page);
            return View(list);
        }

        public IActionResult SetPassword()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> SetPassword(string password)
        {
            var id = await userService.GetLoginUserIDAsync();
            var m = userService.DbSet.Find(id);
            if (m == null)
            {
                return this.NotFound();
            }
            if (string.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", "请填写密码");
            }
            if (ModelState.IsValid)
            {
                userService.SetPassword(id, password);
                return Redirect(Request.Query["returnUrl"]);
            }
            return this.ViewError();
        }
    }
}
